package com.totoro.swagger;

import com.totoro.swagger.config.SwaggerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger starter
 * Created by Niki on 2018/7/6 9:24
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@EnableSwagger2
public class SwaggerAutoConfig {
    @Autowired
    SwaggerProperties properties;

    @Bean
    public Docket api() {
        //默认api类型为swagger_2
        Docket docket = new Docket(DocumentationType.SWAGGER_2);
        docket.groupName(properties.getGroupName());
        ApiSelectorBuilder builder = docket.apiInfo(apiInfo())
                .select();
        if (!StringUtils.isEmpty(properties.getBasePackage())) {
            builder.apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()));
        }
        builder.paths(PathSelectors.any());
        docket = builder.build();
        return docket;
    }

    private ApiInfo apiInfo() {
        ApiInfoBuilder builder = new ApiInfoBuilder();
        if (!StringUtils.isEmpty(properties.getTitle())) {
            builder.title(properties.getTitle());
        }
        if (!StringUtils.isEmpty(properties.getDescription())) {
            builder.description(properties.getDescription());
        }
        if (!StringUtils.isEmpty(properties.getServiceUrl())) {
            builder.termsOfServiceUrl(properties.getServiceUrl());
        }
        if (StringUtils.isEmpty(properties.getVersion())) {
            builder.version(properties.getVersion());
        }

        return builder.build();
    }
}
